package edu.ustb.efws.pipeline.collect.handler;

import edu.ustb.efws.base.domain.Position;
import edu.ustb.efws.pipeline.collect.cache.RiskCache;
import edu.ustb.efws.pipeline.domain.RiskLog;
import edu.ustb.efws.pipeline.domain.ThosLog;
import edu.ustb.efws.pipeline.service.RiskLogService;

import edu.ustb.efws.utils.SafeMath;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Thos设备风险值处理
 *
 * @author TS Group
 */
 class ThosRiskLogHandler extends RiskLogHandler<ThosLog> {

    ThosRiskLogHandler(List<Position> positions, RiskLogService riskLogService) {
        super(positions, riskLogService);
    }

    @Override
    protected Map<Integer, Position> filterMonitorPositions(List<Position> positions) {
        return positions.stream()
                .filter(e -> e.getIptId() == 41)
                .collect(Collectors.toMap(Position::getThoId, e -> e));
    }

    @Override
    protected Position getPosition(Map<Integer, Position> monitorPositions, ThosLog thosLog) {
        return monitorPositions.get(thosLog.getDetectorId());
    }

    @Override
    protected boolean isDetectorActive(Position position) {
        return true;
    }

    @Override
    protected RiskLog buildLog(Position position, ThosLog t){
        RiskLog log = new RiskLog();
        log.setPositionId(position.getId());
        log.setMonth(t.getMonth());
        log.setI(0f);
        log.setU(0f);
        log.setP(0f);
        log.setMaxI(0f);
        log.setIptTime(t.getCollectTime());
        log.setH(t.getH());
        log.setO(t.getO());
        log.setT(t.getT());
        log.setThosTime(t.getCollectTime());
        log.setCreateTime(new Date());

        float[] score = SafeMath.riskScore(log.getI(), log.getU(), 1f, log.getT(), log.getH());
        log.setRiskType((int)score[0]);
        log.setScore(format(score[1]));
        log.setRiskGrade(SafeMath.riskGrade(score[1]));

        RiskCache.INSTANCE.put(log);

        return log;
    }

    private float format(float f){
        return (Math.round(f * 100) * 1.0f)/100;
    }
}
